package com.youens.navigationdrawertest.ui.ps

import android.Manifest
import android.app.ActionBar
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.*
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.*
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import com.xiasuhuei321.loadingdialog.view.LoadingDialog
import com.youens.navigationdrawertest.R
import com.youens.navigationdrawertest.album.GetPhotoFromAlbum
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.sql.Types

class PsFragment : Fragment(), SeekBar.OnSeekBarChangeListener {
    //设置权限请求和活动请求的请求码requestCode
    companion object {
        private const val PERMISSIONS_REQUEST_ALBUM = 1
        private const val PERMISSIONS_REQUEST_CAMERA = 2

        private const val ACTIVITY_REQUEST_ALBUM = 3
        private const val ACTIVITY_REQUEST_CAMERA = 4
    }

    private lateinit var psViewModel: PsViewModel
    lateinit var img: ImageView
    lateinit var open: Button
    lateinit var write: Button
    lateinit var adjust: Button
    lateinit var save: Button
    lateinit var layout: RelativeLayout
    lateinit var hueSeekBar: SeekBar
    lateinit var saturationSeekBar: SeekBar
    lateinit var lumSeekBar: SeekBar
    lateinit var linearLayout: LinearLayout

    lateinit var bitmap: Bitmap //PS前的图片
    lateinit var process_bitmap: Bitmap //PS中的图片
    lateinit var after_bitmap: Bitmap //PS后的图片
    lateinit var loadingDialog: LoadingDialog

    lateinit var photoPath: String

    //标识变量  0-取消触摸事件 1-添加文字
    var flagOnTouch = 0
    var mHue: Float = 0f
    var msaturation: Float = 1f
    var mlum: Float = 1f

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        photoPath = ""
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        psViewModel =
            ViewModelProviders.of(this).get(PsViewModel::class.java)
        val root = inflater.inflate(R.layout.fragment_ps, container, false)
        return root
    }

    override fun onStart() {
        super.onStart()
        img = view!!.findViewById(R.id.imageView1)
        open = view!!.findViewById(R.id.button1)
        write = view!!.findViewById(R.id.button2)
        adjust = view!!.findViewById(R.id.button3)
        save = view!!.findViewById(R.id.button4)
        layout = view!!.findViewById(R.id.Content_Layout)
        hueSeekBar = view!!.findViewById(R.id.hueSeekBar)
        saturationSeekBar = view!!.findViewById(R.id.saturationSeekBar)
        lumSeekBar = view!!.findViewById(R.id.lumSeekBar)
        linearLayout = view!!.findViewById(R.id.linear_Layout)

        linearLayout.setVisibility(View.GONE) // 隐藏调节按钮
        hueSeekBar.max = 255
        saturationSeekBar.max = 255
        lumSeekBar.max = 255
        hueSeekBar.progress = 127
        saturationSeekBar.progress = 127
        lumSeekBar.progress = 127
        hueSeekBar.setOnSeekBarChangeListener(this)
        saturationSeekBar.setOnSeekBarChangeListener(this)
        lumSeekBar.setOnSeekBarChangeListener(this)
        initListener()
    }

    fun showLoading(){
        loadingDialog = LoadingDialog(activity)
        loadingDialog.setLoadingText("保存中...")
        loadingDialog.setSuccessText("保存成功")
        loadingDialog.setFailedText("保存失败")
        loadingDialog.closeSuccessAnim()
        loadingDialog.closeFailedAnim()
        loadingDialog.show()
    }
    fun initListener() {

        img.setOnTouchListener(object : View.OnTouchListener { //触摸事件

            override fun onTouch(v: View, event: MotionEvent): Boolean {
                if (flagOnTouch == 1) {//点击图片弹出键盘
                    var downx = event.x
                    var downy = event.y
                    addWigdet(layout, downx.toInt(), downy.toInt(), createEditText())
                    return true
                } else return false
            }
        })
        open.setOnClickListener {
            linearLayout.visibility = View.GONE // 隐藏调节按钮
            flagOnTouch = 0
            //open()
            hueSeekBar.progress = 127
            saturationSeekBar.progress = 127
            lumSeekBar.progress = 127
            //检查版本是否大于M
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(
                        activity!!.applicationContext,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    ActivityCompat.requestPermissions(
                        activity!!,
                        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                        PERMISSIONS_REQUEST_ALBUM
                    )
                } else {
                    //权限已经被授权，开启相册
                    goAlbum()
                }
            }
        }
        write.setOnClickListener {
            Toast.makeText(activity,"点击图片添加文字",Toast.LENGTH_SHORT).show()
            linearLayout.visibility = View.GONE // 隐藏调节按钮
            flagOnTouch = 1
        }
        adjust.setOnClickListener {
            flagOnTouch = 0
            linearLayout.visibility = View.VISIBLE // 显示调节按钮
        }
        save.setOnClickListener {
            linearLayout.visibility = View.GONE // 隐藏调节按钮
            flagOnTouch = 0
            //verifyStoragePermissions(this)
            saveBitmap() // 保存图片
            showLoading()
        }
    }

    //权限结果回调
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        when (requestCode) {
            //相册权限请求结果
            PERMISSIONS_REQUEST_ALBUM -> {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    goAlbum()
                } else {
                    Toast.makeText(activity, "你拒绝了读取相册权限", Toast.LENGTH_SHORT).show()
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    //相册功能
    private fun goAlbum() {
        val intent = Intent()
        intent.action = Intent.ACTION_PICK
        intent.type = "image/*"
        startActivityForResult(intent, ACTIVITY_REQUEST_ALBUM)
    }

    //活动请求的回调，用requestCode来匹配
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        //相册
        if (requestCode == ACTIVITY_REQUEST_ALBUM && resultCode == Activity.RESULT_OK) {

            photoPath = GetPhotoFromAlbum.getRealPathFromUri(activity!!.applicationContext, data!!.data)!!
            img.setImageURI(Uri.parse(photoPath))
            img.scaleType = ImageView.ScaleType.FIT_CENTER
            bitmap = BitmapFactory.decodeFile(photoPath)
            img.setImageBitmap(bitmap)
            process_bitmap = bitmap
            after_bitmap = bitmap

            super.onActivityResult(requestCode, resultCode, data)
        }

    }

    // 保存图片
    private fun saveBitmap() {
        if (photoPath!=""){
            Thread{
                val f = File(Environment.getExternalStorageDirectory().path + "/cameraTest/" + System.currentTimeMillis() + ".jpg")
                try {
                    val out = FileOutputStream(f)
                    after_bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)
                    out.flush()
                    out.close()
                    activity!!.runOnUiThread{
                        loadingDialog.loadSuccess()
                        Toast.makeText(activity,"保存成功！",Toast.LENGTH_SHORT).show()
                    }
                } catch (e: Exception) {
                    activity!!.runOnUiThread{
                        loadingDialog.loadFailed()
                        Toast.makeText(activity,"保存失败！",Toast.LENGTH_SHORT).show()
                    }
                    e.printStackTrace()
                }
            }.start()
        }
        else{
            Toast.makeText(activity,"没有图片！",Toast.LENGTH_SHORT).show()
        }
    }


    //弹出键盘实现
    fun addWigdet(layout: RelativeLayout, x: Int, y: Int, v: EditText) {
        val params: RelativeLayout.LayoutParams = RelativeLayout.LayoutParams(
            ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT
        )
        params.leftMargin = x
        params.topMargin = y
        layout.addView(v, params)
        v.isFocusable = true
        v.isFocusableInTouchMode = true
        v.requestFocus()
        v.setTextColor(Color.RED)
        v.background.alpha = Types.NULL
        //v.isCursorVisible = false
        val inputManager: InputMethodManager =
            v.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputManager.showSoftInput(v, 0)
        v.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                val display = activity!!.windowManager.defaultDisplay
                var proportion = bitmap.width.toFloat() / display.width.toFloat()
                saveText(
                    s.toString(),
                    x.toFloat() * proportion + 7,
                    y.toFloat() * proportion + 65
                )
                //重新加载图片
                img.scaleType = ImageView.ScaleType.FIT_CENTER
                img.setImageBitmap(after_bitmap)
                v.isVisible = false
            }

            override fun beforeTextChanged(
                s: CharSequence?,
                start: Int,
                count: Int,
                after: Int
            ) {
                //输入前的监听
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                //输入文字产生变化的监听
            }
        })
        v.setText("")
    }

    //键盘添加EditText
    fun createEditText(): EditText {
        val et = EditText(activity)
        val params = ActionBar.LayoutParams(
            ActionBar.LayoutParams.WRAP_CONTENT,
            ActionBar.LayoutParams.WRAP_CONTENT
        )
        et.layoutParams = params
        return et
    }

    fun saveText(text: String, paddingLeft: Float, paddingTop: Float) {
        //添加文字
        val p = Paint()
        p.color = Color.RED
        p.textSize = 120.toFloat()
        var bitmap = after_bitmap
        var bitmapConfig = bitmap.config
        bitmap = bitmap.copy(bitmapConfig, true)
        val canvas = Canvas(bitmap)
        canvas.drawText(text, paddingLeft, paddingTop, p)
        process_bitmap = bitmap
        after_bitmap = bitmap
    }

    //以下皆为调节功能
    override fun onStartTrackingTouch(seekBar: SeekBar) {

    }

    override fun onStopTrackingTouch(seekBar: SeekBar) {
        after_bitmap = handleImage(process_bitmap, mHue, msaturation, mlum)
    }

    override fun onProgressChanged(
        seekBar: SeekBar,
        progress: Int,
        fromUser: Boolean
    ) {
        when (seekBar.id) {
            R.id.hueSeekBar ->         //转化公式
                mHue = (progress - 127) * 1.0f / 127 * 180
            R.id.saturationSeekBar ->         //转化公式
                msaturation = progress * 1.0f / 127
            R.id.lumSeekBar ->         //转化公式
                mlum = progress * 1.0f / 127
        }
        img.setImageBitmap(handleImage(process_bitmap, mHue, msaturation, mlum))
    }

    fun handleImage(
        bm: Bitmap,
        hue: Float,
        saturation: Float,
        lum: Float
    ): Bitmap {
        //确定图片的大小和格式。
        val bmp = Bitmap.createBitmap(bm.width, bm.height, Bitmap.Config.ARGB_8888)
        //      新建画布
        val canvas = Canvas(bmp)
        //      新建画笔
        val paint = Paint(Paint.ANTI_ALIAS_FLAG)
        //      设置色相
        val hueMatrix = ColorMatrix()
        hueMatrix.setRotate(0, hue)
        hueMatrix.setRotate(1, hue)
        hueMatrix.setRotate(2, hue)
        //      设置饱和度
        val saturationMatrix = ColorMatrix()
        saturationMatrix.setSaturation(saturation)
        //      设置亮度
        val lumMatrix = ColorMatrix()
        lumMatrix.setScale(lum, lum, lum, 1f)
        //      将三种效果进行融合
        val imageMatrix = ColorMatrix()
        imageMatrix.postConcat(hueMatrix)
        imageMatrix.postConcat(saturationMatrix)
        imageMatrix.postConcat(lumMatrix)
        //      绘制图片
        paint.colorFilter = ColorMatrixColorFilter(imageMatrix)
        canvas.drawBitmap(bm, 0.toFloat(), 0.toFloat(), paint)
        //将更改后的图片进行返回。
        return bmp
    }
}

